package com.flow.framework.core.system.thread.pool.factory;

import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.util.verify.VerifyUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池的线程工厂
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/23
 */
public class DefaultThreadFactory implements ThreadFactory {

    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public DefaultThreadFactory(String threadNamePrefix) {
        if (VerifyUtil.isEmpty(threadNamePrefix)) {
            throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
        }
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    /**
     * @inheritDoc
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
